package xhwl.insurance.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;
import rx.functions.Action1;
import xhwl.android.common.util.SPUtil;
import xhwl.android.common.util.StringUtil;
import xhwl.insurance.BaseActivity;
import xhwl.insurance.R;
import xhwl.insurance.adapter.MessageCenterAdapter;
import xhwl.insurance.customView.DelListView;
import xhwl.insurance.customView.PullToRefreshView;
import xhwl.insurance.http.api.MarkMsgStatusApi;
import xhwl.insurance.http.api.MessageListApi;
import xhwl.insurance.http.api.NewProcessInfoApi;
import xhwl.insurance.http.bean.resp.MessageResp;
import xhwl.insurance.http.bean.resp.ProcessListResp;
import xhwl.insurance.http.bean.resp.ResponseError;
import xhwl.insurance.upgrade.UpgradeEvent;
import xhwl.insurance.upgrade.UpgradeMgr;
import xhwl.insurance.util.PermisionUtils;
import xhwl.insurance.util.SpUtil;
import xhwl.insurance.util.ToastUtil;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

/**
 * Created by fuyi on 2017/8/24.
 */

public class MessageCenterActivity extends BaseActivity implements View.OnClickListener {
    private static String[] PERMISSION = {Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static final String TAG = MessageCenterActivity.class.getSimpleName();
    //    private PullToRefreshListView mListView;
    private MessageCenterAdapter adapter;
    private ArrayList<MessageResp> mList = new ArrayList<>();
//    PullToRefreshView mPullToRefreshView;
    RefreshLayout refreshLayout;
    DelListView mListView;
    LinearLayout emptyView;
    ImageView nodateImg;
    int mPage = 1, pullState = PullToRefreshView.PullState.PULL_DOWN;
    private LinearLayout mReply;
    private Boolean msgFlay;
    private ImageView mRedPort;
    private String back_state;
    private ImageView title_left_imageview;

    //    ListViewSlideAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        msgFlay = SpUtil.getBoolean(SpUtil.REPLY_MAG_FLAG, true);
        setContentView(R.layout.activity_message_center);
        back_state = getIntent().getStringExtra("BACK_STATE");
    }


    @Override
    public void initViews() {
        initTitleViews();
        emptyView = (LinearLayout) findViewById(R.id.emptyView);
        nodateImg = (ImageView) findViewById(R.id.nodata);
        refreshLayout = (RefreshLayout)findViewById(R.id.refreshLayout);
        mListView = (DelListView) findViewById(R.id.mListView);
        mListView.setEmptyView(emptyView);
        title_left_imageview = (ImageView) findViewById(R.id.title_left_imageview);
        adapter = new MessageCenterAdapter(MessageCenterActivity.this, mList);
        mListView.setAdapter(adapter);
        mReply = (LinearLayout) findViewById(R.id.reply);//回复我的
        //消息的小红点
        mRedPort = (ImageView) findViewById(R.id.iv_red_port);
        if (msgFlay) {
            mRedPort.setVisibility(View.VISIBLE);
        } else {
            mRedPort.setVisibility(View.GONE);
        }
        refreshLayout.setEnableLoadmore(false);//没有分页，设置不能加载更多，分页以后直接enable即可
    }

    @Override
    protected void processOper() {
        super.processOper();
        if(SpUtil.getBoolean(SpUtil.REPLY_MAG_FLAG,false)){
            mRedPort.setVisibility(View.VISIBLE);
        }else{
            mRedPort.setVisibility(View.GONE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    new UpgradeMgr().checkVersion(MessageCenterActivity.this);
                } else {
                    PermisionUtils.dialog(this, "读取手机存储");
                }
                break;
        }
    }

    @Override
    protected void setUpTitleView() {
        super.setUpTitleView();
        titleTextView.setText("消息中心");

        rightTextView.setText("全部已读");
    }

    @Override
    public void initListener() {

//        adapter.setOnClickListenerEditOrDelete(new ListViewSlideAdapter.OnClickListenerEditOrDelete() {
//            @Override
//            public void OnClickListenerDelete(int position) {
//                xhwl.android.common.util.ToastUtil.showToast(mContext,"delete"+position);
//            }
//        });
        title_left_imageview.setOnClickListener(this);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getMessages(1);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                getMessages(mPage+1);
            }
        });
        mListView.setDelButtonClickListener(new DelListView.DelButtonClickListener() {
            @Override
            public void clickHappend(final int position) {
                final MessageResp data = mList.get(position);
                String memberId = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
                if (StringUtil.isEmpty(memberId)) {
                    return;
                }
                //删除
                MarkMsgStatusApi api = new MarkMsgStatusApi(memberId, data.PUSH_ID, "2");
                HttpManager.getInstance().dealHttp(MessageCenterActivity.this, api, new OnNextListener<ResponseError>() {
                    @Override
                    public void onNext(ResponseError error) {
                        if (error != null && error.isSuccess()) {
                            mList.remove(position);
                            adapter.notifyDataSetChanged();
                        }
                    }
                });
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final MessageResp data = mList.get(position);
                String memberId = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
                if (StringUtil.isEmpty(memberId)) {
                    return;
                }
                if ("0".equals(data.READ_IF)) {
                    //标记已读
                    MarkMsgStatusApi api = new MarkMsgStatusApi(memberId, data.PUSH_ID, "1");
                    HttpManager.getInstance().dealHttp(MessageCenterActivity.this, api, new OnNextListener<ResponseError>() {
                        @Override
                        public void onNext(ResponseError error) {
                            if (error != null && error.isSuccess()) {
                                data.READ_IF = "1";
                                adapter.notifyDataSetChanged();
                            }
                        }
                    });
                }
                if ("0".equals(data.PUSH_TYPE)) {//版本通知
//                    if (PermisionUtils.islacksOfPermission(mContext, PERMISSION[1])) {
//                        ToastUtil.showToast(mContext, "请打开提示对应权限,否则将影响重要功能使用");
//                        ActivityCompat.requestPermissions(MessageCenterActivity.this, PERMISSION, 1);
//                    } else {
//                        new UpgradeMgr().checkVersion(MessageCenterActivity.this);
//                    }
                    requestPermission();

                } else {//系统通知
                    if (!StringUtil.isEmpty(data.BUY_ID)) {
                        NewProcessInfoApi api = new NewProcessInfoApi(data.BUY_ID);
                        HttpManager.getInstance().dealHttp(MessageCenterActivity.this, api, new OnNextListener<ProcessListResp>() {
                            @Override
                            public void onNext(ProcessListResp resp) {
                                if (resp != null) {
                                    Intent intent = new Intent(mContext, CardDealDetialActivity.class);
                                    intent.putExtra(CardDealDetialActivity.BEAN, resp);
                                    startActivity(intent);
                                }
                            }
                        });
                    }

                }

            }
        });
        rightTextView.setOnClickListener(this);
        mReply.setOnClickListener(this);
    }

    private void requestPermission() {
        new RxPermissions(this).request(Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        if (granted) {
                            new UpgradeMgr().checkVersion(MessageCenterActivity.this);
                        } else {
                            Log.e(TAG, "用户拒绝开启存储");
                            PermisionUtils.dialog(MessageCenterActivity.this, "读取手机存储");
                        }
                    }

                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_right_textview:
                String memberId = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
                if (StringUtil.isEmpty(memberId)) {
                    return;
                }
                //标记已读
                MarkMsgStatusApi api = new MarkMsgStatusApi(memberId, "", "1");
                HttpManager.getInstance().dealHttp(MessageCenterActivity.this, api, new OnNextListener<ResponseError>() {
                    @Override
                    public void onNext(ResponseError error) {
                        if (error != null && error.isSuccess()) {
                            loadData();
                            SpUtil.putBoolean(SpUtil.REPLY_MAG_FLAG, false);
                            mRedPort.setVisibility(View.GONE);

                        }
                    }
                });
                break;
            case R.id.reply:
                Intent intent = new Intent();
                intent.setClass(MessageCenterActivity.this, ReplyListActivity.class);
                startActivity(intent);
                break;
            case R.id.title_left_imageview:
                if(back_state.equals("1")) {
                    startActivity(new Intent(MessageCenterActivity.this, MainActivity.class)
                            .putExtra("BACK_STATE","1"));
                    finish();
                }else {
                    finish();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void loadData() {
        getMessages(1);
    }

    public void getMessages(final int page) {
        String memberId = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
        if (StringUtil.isEmpty(memberId)) {
            return;
        }
        MessageListApi api = new MessageListApi(memberId);
        HttpManager.getInstance().dealHttp(MessageCenterActivity.this, api, new OnNextListener<ArrayList<MessageResp>>() {
            @Override
            public void onNext(ArrayList<MessageResp> resp) {
                if (page==1) {//下拉刷新
                    refreshLayout.finishRefresh(true);
                    mPage = page;
                    mList.clear();
                    mList.addAll(resp);
                    if(resp.size()>0){
                        rightTextView.setVisibility(View.VISIBLE);
                    }
                    else
                    {
                        rightTextView.setVisibility(View.GONE);
                    }
                    adapter.notifyDataSetChanged();
//                    if (resp.size() == 0) {
//                        emptyView.setVisibility(View.VISIBLE);
//                    } else {
//                        emptyView.setVisibility(View.GONE);
//                    }
                } else {
                    if (resp.size() == 0) {
                        refreshLayout.setLoadmoreFinished(true);//没有加载到数据，隐藏下拉
                    } else {
                        refreshLayout.finishLoadmore(true);
                        mPage = page + 1;
                        mList.addAll(resp);
                        adapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                if (page==1) {//下拉刷新
                    refreshLayout.finishRefresh(false);
                }else{
                    refreshLayout.finishLoadmore(false);
                }
                xhwl.android.common.util.ToastUtil.showToast(mContext, "请求失败，请稍后再试");
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if(SpUtil.getBoolean(SpUtil.REPLY_MAG_FLAG,false)){
            mRedPort.setVisibility(View.VISIBLE);
        }else{
            mRedPort.setVisibility(View.GONE);
        }

    }

    public void onEvent(Object obj) {
        if (obj instanceof UpgradeEvent) {
            UpgradeEvent event = (UpgradeEvent) obj;
            if (event.isDownloadComplete()) {
                new UpgradeMgr().checkVersion(MessageCenterActivity.this);
            } else if (event.isStartDownload()) {
                ToastUtil.showToast(this, "开始下载...");
            } else if (event.isNewest()) {
                ToastUtil.showToast(this, "当前已是最新版本");
            } else if (event.isDownloading()) {
                ToastUtil.showToast(this, "下载中...");
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

        if (null != PermisionUtils.alertDialog)
            PermisionUtils.alertDialog.dismiss();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if(back_state.equals("1")) {
                startActivity(new Intent(MessageCenterActivity.this, MainActivity.class)
                        .putExtra("BACK_STATE","1"));
                finish();
            }else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
